package com.screen.screendisplay.service.impl.ne;

import com.screen.screendisplay.entity.ne.NeProdoperSalesPurchase;
import com.screen.screendisplay.mapper.ne.NeProdoperSalesPurchaseMapper;
import com.screen.screendisplay.service.ne.NeProdoperSalesPurchaseService;
import com.screen.screendisplay.vo.ne.NeSalesPurchaseVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 购网电量和购网电价表 服务实现类
 * </p>
 *
 * @author xuesong
 * @since 2025-08-23
 */
@Service
public class NeProdoperSalesPurchaseServiceImpl extends ServiceImpl<NeProdoperSalesPurchaseMapper, NeProdoperSalesPurchase> implements NeProdoperSalesPurchaseService {

    @Override
    public List<NeSalesPurchaseVO> getSalesPurchase(Integer year) {
        QueryWrapper<NeProdoperSalesPurchase> queryWrapper = new QueryWrapper<>();
        
        if (year != null) {
            queryWrapper.eq("year", year);
        } else {
            // 如果没有指定年份，获取最近12个月的数据
            LocalDate now = LocalDate.now();
            LocalDate oneYearAgo = now.minusMonths(12);
            queryWrapper.ge("date", oneYearAgo);
        }
        
        // 按年份、月份降序排列，获取最新的数据
        queryWrapper.orderByDesc("year", "month");
        
        List<NeProdoperSalesPurchase> entityList = this.list(queryWrapper);
        
        // 转换为VO对象
        return entityList.stream().map(entity -> {
            NeSalesPurchaseVO vo = new NeSalesPurchaseVO();
            vo.setYear(entity.getYear());
            vo.setMonth(entity.getMonth());
            vo.setPurchasePower(entity.getPurchasePower());
            vo.setPurchasePrice(entity.getPurchasePrice());
            return vo;
        }).collect(Collectors.toList());
    }

}
